# -*- coding: utf-8 -*-
#
# Author:: hanjunfeng
# Date:: 2021/1/4


# -*- coding: utf-8 -*-
#
# Author:: hanjunfeng
# Date:: 2021/1/4
import os

from lib.list_ import list_to_text
from lib.log_ import logger
from lib.path_ import with_add_suffix_before_extension
from lib.text_ import get_text_data


def do_something_with_list(func_name, data_list, *args):
    '''
    输入函数和一个list，若list某项被非正常执行则终止，并返回未执行的元素
    '''
    current_index = None
    for item in data_list:
        logger.info("item:%s" % str(item))
        try:
            func_name(item, *args)
        except Exception as e:
            print(repr(e))
            current_index = data_list.index(item)
            break
    if current_index == None:
        return []
    else:
        return data_list[current_index:]


def do_something_with_csv(func_name, filename, *args):
    filename_tmp = with_add_suffix_before_extension(filename)
    if os.path.isfile(filename_tmp):
        filename = filename_tmp
    data_list = get_text_data(filename, ",")

    res_list = do_something_with_list(func_name, data_list, *args)

    if res_list == []:
        try:
            os.remove(filename_tmp)
        except:
            pass
    else:
        list_to_text(res_list, filename_tmp)


if __name__ == "__main__":
    def do_something(item):
        if item == 3:
            raise Exception


    l = [1, 2, 3, 4, 5]
    res = do_something_with_list(do_something, l)
    print(res)
